//当页面中DOM结构加载完毕之后，可以调用该函数
window.addEventListener('DOMContentLoaded',async()=>{
    const {data:{rows}}=await fetchTeacherListApi()
    renderTeacherList(rows);//调用渲染完成页面的渲染
    document.querySelector('#searchBtn').addEventListener('click',async()=>{
        let name=document.querySelector('#nameInput').value
        const {data:{rows}}=await fetchSearchApi(name)
        renderTeacherList(rows)
    })
    //为删除按钮绑定事件
    document.querySelector("tbody").addEventListener('click',async e=>{
        if(e.target.className=="delBtn"){
           let id=e.target.parentElement.parentElement.firstElementChild.innerText
           const {code,message,data:{rows}}=await delTeacherApi(id)
           if(code){
            alert(message)
            renderTeacherList(rows)
           }
        }
    })
    //为修改按钮绑定单击事件
    document.querySelector('tbody').addEventListener('click',e=>{
        if(e.target.className=="updateBtn"){
            let id=e.target.parentElement.parentElement.firstElementChild.innerText
            location=`upateTeacher.html?tid=${id}`
        }
    })
})
const renderTeacherList=(rows)=>{
  document.querySelector("tbody").innerHTML=rows.map(item=>
    `<tr>
        <td>${item.tid}</td>
        <td>${item.tname}</td>
        <td>${item.age}</td>
        <td>${item.lession}</td>
        <td>
            <button class="delBtn">删除</button>
            <button class="updateBtn">修改</button>
        </td>
     </tr>`).join("")
}

const delTeacherApi=id=>{
    return new Promise((resolve,reject)=>{
        const xhr=new XMLHttpRequest()
        xhr.open('DELETE',`/teachers/del/${id}`,true)
        xhr.send()
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){
                if(xhr.status==200){
                    resolve(JSON.parse(xhr.responseText))
                }
            }
        }
    })
}

const fetchSearchApi=(name)=>{
    return new Promise((resolve,reject)=>{
        const xhr=new XMLHttpRequest()
        xhr.open("GET",`/teachers/search?name=${name}`,true)
        xhr.send()
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){
                if(xhr.status==200){
                   resolve(JSON.parse(xhr.responseText))
                }
            }
        }
    })
}

const fetchTeacherListApi=()=>{
   return new Promise((resolve,reject)=>{
        //创建XMLHttpRequest对象
        const xhr=new XMLHttpRequest()
        //进行初始化
        xhr.open('GET','/teachers/list',true)
        //发送请求
        xhr.send()
        //设置回调函数
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){
                if(xhr.status==200){
                   resolve(JSON.parse(xhr.responseText))
                }
            }
        }
    })
}